import { WebVariable } from "../data/WebVariable";
// import {HttpClient} from "../service/Http/HttpClient"
// import { UI } from "../service/Utils/UI";
import $ from "jquery";
import { AvailableLanguage } from "./AvailableLanguage";
import { Language } from "./Language";

/**语言配置 */
export class LanguageSettings {
  /**
   * 设置界面语言
   * @param id
   * @param reload 是否加载新设置的语言
   */
  static async setLanguage(id: AvailableLanguage, reload: boolean = true) {
    localStorage.setItem("language", id);
    if (reload) {
      await this.load();
    }
  }

  /**获取默认的界面语言 */
  static getDefault(): AvailableLanguage {
    return (
      AvailableLanguage[WebVariable.defaultLanguage as AvailableLanguage] ??
      AvailableLanguage["zh-cn"]
    );
  }

  /**加载语言 */
  static async load() {
    let lanKey = this.getDefault();
    const key = localStorage.getItem("language");
    if (typeof key == "string") {
      lanKey = AvailableLanguage[key as AvailableLanguage] ?? lanKey;
    }
    try {
      const languageResource = await import(`./lans/${lanKey}`);
      $.extend(Language, languageResource.default);
      Object.assign(WebVariable, Language.webVariable);
      document.title = WebVariable.title;
    } catch (e) {
      alert(`Cannot load language from file: ${lanKey}`);
      console.error(e);
    }
  }
}
